package com.gamelife.web.controller.system;


import com.gamelife.web.config.redis.RedisCache;
import com.gamelife.web.constant.Constants;
import com.gamelife.web.domain.AjaxResult;
import com.gamelife.web.domain.entity.SysMenu;
import com.gamelife.web.domain.entity.SysUser;
import com.gamelife.web.domain.modle.LoginBody;
import com.gamelife.web.service.SysLoginService;
import com.gamelife.web.service.SysMenuService;
import com.gamelife.web.service.SysUserService;
import com.gamelife.web.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Api(tags = "登录")
public class SysLoginController {

    @Resource
    private SysLoginService sysLoginService;

    @Resource
    private SysMenuService sysMenuService;


    @Resource
    private SysUserService sysUserService;

    @Resource
    private RedisCache redisCache;

    @PostMapping("login")
    @ApiOperation("登录接口")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();

        String token = sysLoginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put("token", token);
        return ajax;
    }

    @GetMapping("logout")
    @ApiOperation("登出接口")
    public AjaxResult logout(){
        Long userId = SecurityUtils.getUserId();
        redisCache.deleteObject(Constants.LOGIN_USER_KEY+userId);
        return AjaxResult.success("退出成功");
    }


    @GetMapping("getRouters")
    @ApiOperation("获取当前用户的路由列表")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = sysMenuService.selectSysMenuListByUserId(userId);
        // 构建菜单树结构
        return AjaxResult.success(sysMenuService.buildSysMenuTree(menus));
    }

    @GetMapping("getUserInfo")
    @ApiOperation("获取当前用户的个人信息")
    public AjaxResult getUserInfo(){
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserByUserId(userId);
        sysUser.setPassword(null);
        return AjaxResult.success(sysUser);
    }
}
